/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q0002.java
 * @Author : WangRuoyu
 * @Date 2023/1/25 19:17
 */

package leetcode;

import util.LinkList;
import util.ListNode;

public class Q0002 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode h = new ListNode(-1, l1);
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode s = h;

        int c = 0;
        while (p1 != null && p2 != null) {
            int tmp = p1.val;
            p1.val = (p1.val + p2.val + c) % 10;
            c = (tmp + p2.val + c) / 10;
            p1 = p1.next;
            p2 = p2.next;
            s = s.next;
        }

        if (p1 == null) {
            p1 = p2;
            s.next = p1;
        }

        while (c != 0 && p1 != null) {
            int tmp = p1.val;
            p1.val = (p1.val + c) % 10;
            c = (tmp + c) / 10;
            p1 = p1.next;
            s = s.next;
        }

        if (c != 0) {
            s.next = new ListNode(c);
        }

        return h.next;
    }

    public static void main(String[] args) {
        Q0002 sl = new Q0002();
        ListNode l1 = LinkList.createList(new int[]{9, 9, 9});
        ListNode l2 = LinkList.createList(new int[]{9});
        ListNode p = sl.addTwoNumbers(l1, l2);
        LinkList.printList(p);
    }
}
